package client // Package client import "xemo.top/docker/docker/client"
import (
	"fmt"
	"net/http"
	"xemo.top/docker/docker/api/types/versions"
	"xemo.top/docker/docker/errdefs"
)

// NewVersionError 如果所需的APIVersion小于当前支持的版本，则返回错误
// NewVersionError returns an error if the APIVersion required if less than the current supported version
func (cli *Client) NewVersionError(APIrequired, feature string) error {
	if cli.version != "" && versions.LessThan(cli.version, APIrequired) {
		return fmt.Errorf("%q requires API version %s,but the Docker daemon API version is %s", feature, APIrequired, cli, cli.version)
	}
	return nil
}

// errConnectionFailed 实现连接失败时返回的错误
// errConnectionFailed implements an error returned when connection failed
type errConnectionFailed struct {
	host string
}

// Error returns a string representation of an errConnectionFailed
func (err errConnectionFailed) Error() string {
	if err.host == "" {
		return "Cannot connect to the Docker daemon.Is the docker daemon running on this host?"
	}
	return fmt.Sprintf("Cannont connect to the Docker daemon at %s.Is the docker daemon running?", err.host)
}

// ErrorConnectionFailed 当连接到docker守护程序失败时，在错误消息中返回host错误。
// ErrorConnectionFailed returns an error with host in the error message when connection to docker daemon failed.
func ErrorConnectionFailed(host string) error {
	return errConnectionFailed{host: host}
}

type objectNotFoundError struct {
	object string
	id     string
}

func (e objectNotFoundError) NotFound() {}
func (e objectNotFoundError) Error() string {
	return fmt.Sprintf("Error: No such %s:%s", e.object, e.id)
}

func wrapResponseError(err error, resp serverResponse, object, id string) error {
	switch {
	case err == nil:
		return nil
	case resp.statusCode == http.StatusNotFound:
		return objectNotFoundError{object: object, id: id}
	case resp.statusCode == http.StatusNotImplemented:
		return errdefs.NotImplemented(err)
	default:
		return err
	}
}
